﻿using System;
using System.Collections.Generic;
using System.Threading;
using System.ComponentModel;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;
using System.Net;
using System.Web;
using System.Xml;
using LitJson;
using MediaPortal.GUI.Library;
using MediaPortal.Configuration;

namespace MediaPortal.Plugins.Trailers.Common {
    public class Utils {
        public static string NumPadEncode(string input) {
            string rtn = input.Trim();
            rtn = Regex.Replace(rtn, @"[abc]", "2", RegexOptions.IgnoreCase);
            rtn = Regex.Replace(rtn, @"[def]", "3", RegexOptions.IgnoreCase);
            rtn = Regex.Replace(rtn, @"[ghi]", "4", RegexOptions.IgnoreCase);
            rtn = Regex.Replace(rtn, @"[jkl]", "5", RegexOptions.IgnoreCase);
            rtn = Regex.Replace(rtn, @"[mno]", "6", RegexOptions.IgnoreCase);
            rtn = Regex.Replace(rtn, @"[pqrs]", "7", RegexOptions.IgnoreCase);
            rtn = Regex.Replace(rtn, @"[tuv]", "8", RegexOptions.IgnoreCase);
            rtn = Regex.Replace(rtn, @"[wxyz]", "9", RegexOptions.IgnoreCase);
            rtn = Regex.Replace(rtn, @"[\s]", "0", RegexOptions.IgnoreCase);
            return rtn;
        }

        public static string GetWebData(string url)
    {
      string _data = string.Empty;

      int tryCount = 0;
      int maxRetries = 3;
      int timeout = 0;
      int timeoutIncrement = 5000;

      Log.Debug("[MyTrailers] GET: {0}", url);
      while (_data == string.Empty)
      {
        try
        {
          tryCount++;
          HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
          request.Timeout = timeout + (timeoutIncrement * tryCount);
          HttpWebResponse response = (HttpWebResponse)request.GetResponse();
          
          // if resource doesn't exist don't retry
          if (response.StatusCode == HttpStatusCode.NotFound)
              break;

          Stream resultData = response.GetResponseStream();
          Encoding encoding = Encoding.UTF8;
          if (response.CharacterSet != string.Empty)
              encoding = Encoding.GetEncoding(response.CharacterSet);

          StreamReader reader = new StreamReader(resultData, encoding, true);
          _data = reader.ReadToEnd(); 
          resultData.Close();
          reader.Close();
          response.Close();
        }
        catch (WebException e)
        {
            if (e.Status == WebExceptionStatus.ProtocolError) {
                HttpStatusCode statusCode = ((HttpWebResponse)e.Response).StatusCode;
                if (statusCode == HttpStatusCode.NotFound) {
                    break;
                }
            }

            Log.Error("{0}", e.Message);
            if (tryCount == maxRetries) {
                Log.Error("[MyTrailers] Error connecting to {0} . Reached retry limit of {1}", url, maxRetries);
                return _data;
            }
        }
      }

      return _data;
    }

        // Json Data Grabber
        public static JsonData GetJson(string url) {
            string WebData = GetWebData(url);
            if (WebData != string.Empty) {
                try {
                    // attempts to convert the returned string into a JsonData object
                    JsonData data = JsonMapper.ToObject(WebData);
                    return data;
                }
                catch (JsonException e) {
                    Log.Error("Error parsing results from {0} as JSON: {1}", url, e.Message);
                }
            }
            return null;
        }

        // XML Data Grabber
        public static XmlNode GetXml(string url) {
            string WebData = GetWebData(url);
            if (WebData != string.Empty) {
                try {
                    // attempts to convert the returned string into an XmlDocument
                    XmlDocument doc = new XmlDocument();
                    doc.LoadXml(WebData);
                    XmlNode root = doc.FirstChild.NextSibling;
                    return root;
                }
                catch (XmlException e) {
                    Log.Error("Error parsing results from {0} as XML: {1}", url, e.Message);
                }
            }

            return null;
        }

        #region Yet To Be Implemented (Download Trailers)

        public static void DownloadFileInBackground(string address, string location) {
            WebClient client = new WebClient();
            Uri uri = new Uri(address);

            // Specify that the DownloadFileCallback method gets called
            // when the download completes.
            client.DownloadFileCompleted += new AsyncCompletedEventHandler(onDownloadFileCompleted);
            // Specify a progress notification handler.
            client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(onDownloadFileProgress);
            client.DownloadFileAsync(uri, location);
            //client.DownloadDataAsync(uri)
            //client.DownloadStringAsync(uri)
        }

        private static void onDownloadFileProgress(object sender, DownloadProgressChangedEventArgs e) {
            // Displays the operation identifier, and the transfer progress.
            //Console.WriteLine("{0}    downloaded {1} of {2} bytes. {3} % complete...",
            //    (string)e.UserState,
            //    e.BytesReceived,
            //    e.TotalBytesToReceive,
            //    e.ProgressPercentage);
        }

        private static void onDownloadFileCompleted(object sender, AsyncCompletedEventArgs e) {

        }

        #endregion

        public Utils() {
        }

    }
}
